package com.gzhryc.tenxun.map;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.tenxun.map.msg.req.ChangeLocationRequest;
import com.gzhryc.tenxun.map.msg.req.GeocoderRequest;
import com.gzhryc.tenxun.map.msg.resp.ChangeLocationResponse;
import com.gzhryc.tenxun.map.msg.resp.GeocoderResponse;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class TenxunMapApi {

	public static ChangeLocationResponse changeLocation(ChangeLocationRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("http")
		        .setHost("apis.map.qq.com")
		        .setPath("/ws/coord/v1/translate")
		        .setParameter("locations",request.getLocations())
		        .setParameter("type",request.getType().toString())
		        .setParameter("key",request.getKey())
		        .build();
			
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				//System.out.println(str);
				return JsonTools.fromJson(str, ChangeLocationResponse.class);
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	public static GeocoderResponse getGeocoder(GeocoderRequest request){
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			URI uri = new URIBuilder()
		        .setScheme("http")
		        .setHost("apis.map.qq.com")
		        .setPath("/ws/geocoder/v1/")
		        .setParameter("location",request.getLocation())
		        .setParameter("coord_type",request.getCoord_type().toString())
		        .setParameter("key",request.getKey())
		        .build();
			
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				//System.out.println(str);
				return JsonTools.fromJson(str, GeocoderResponse.class);
			}
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
}
